package com.cybertron.ironhide.manage.common.job;

import java.io.File;
import java.net.MalformedURLException;
import java.util.List;
import java.util.TimeZone;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.cybertron.ironhide.manage.common.Constants;
import com.cybertron.ironhide.manage.common.base.Pager;
import com.cybertron.ironhide.manage.domain.Article;
import com.cybertron.ironhide.manage.service.ArticleService;
import com.cybertron.ironhide.manage.util.PageUtil;
import com.redfin.sitemapgenerator.W3CDateFormat;
import com.redfin.sitemapgenerator.W3CDateFormat.Pattern;
import com.redfin.sitemapgenerator.ChangeFreq;
import com.redfin.sitemapgenerator.WebSitemapGenerator;
import com.redfin.sitemapgenerator.WebSitemapUrl;
import com.redfin.sitemapgenerator.WebSitemapUrl.Options;

@Component
public class SiteMapGenJob {
	private Log logger = LogFactory.getLog(SiteMapGenJob.class);

	@Resource
	private ArticleService articleService;

	public void run() {
		try {
			logger.info("sitmap gening....");
			WebSitemapGenerator wsg = getWsg();
			if (wsg == null) {
				return;
			}

			wsg.addUrl(Constants.WEB_ROOT_PATH);
			createSiteMap(new Pager(), wsg);
			wsg.write();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}

	private void createSiteMap(Pager pager, WebSitemapGenerator wsg)
			throws MalformedURLException {
		List<Article> articles = articleService.selectBySelective(
				new Article(), pager);
		if (articles != null && articles.size() != 0) {
			for (Article article : articles) {
				Options options = new Options(Constants.WEB_ROOT_PATH
						+ "/article/" + PageUtil.encodeUrl(article.getTitle())
						+ ".html").lastMod(article.getModifyDate()).changeFreq(
						ChangeFreq.DAILY);
				WebSitemapUrl url = new WebSitemapUrl(options);
				wsg.addUrl(url);
			}
			Pager newPager = new Pager(pager.getPageNum() + 1);
			createSiteMap(newPager, wsg);
		}
	}

	private WebSitemapGenerator getWsg() {
		W3CDateFormat dateFormat = new W3CDateFormat(Pattern.SECOND);
		dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
		try {
			WebSitemapGenerator wsg = WebSitemapGenerator
					.builder(Constants.WEB_ROOT_PATH,
							new File(Constants.RESOURCE_ROOT_PATH))
					.dateFormat(dateFormat).build();
			return wsg;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}
	}
}
